﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using KerriganService.DAC;
using KerriganDataContract.Facture;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace KerriganDataContract
{
    class FactureDAC
    {

        public static void PayBill (int customerId, List<string> detailList, List<SessionToPayDC> sessionsToPay)
        {
            using (KerriganDBEntities db = new KerriganDBEntities())
            {

                try
                {
                    TFactureGenerated factureGenerated = new TFactureGenerated();
                    factureGenerated.Date = DateTime.Now;
                    db.TFactureGenerateds.AddObject(factureGenerated);
                    db.SaveChanges();
                    int idFacture = factureGenerated.IdFacture;
                    foreach (string element in detailList)
                    {
                        string[] component = element.Split('@');
                        TFactureContent content = new TFactureContent();
                        content.Designation = component[0];
                        content.Price = Int32.Parse(component[1]);
                        content.IdFactureGeneratedFK = idFacture;
                        db.TFactureContents.AddObject(content);
                        db.SaveChanges();

                    }
                    List<int> listSessionId = new List<int>();
                    foreach(SessionToPayDC session in sessionsToPay ){
                        listSessionId.Add(session.IdSession);
                    }
                    foreach(TSessionApplicant sessionApplicant in db.TSessionApplicants.ToList()){
                        Debug.WriteLine(listSessionId.Contains(sessionApplicant.IdSessionApplicant));
                        if (sessionApplicant.IdFactureGenerated == null && sessionApplicant.IdApplicantFK == customerId && listSessionId.Contains(sessionApplicant.IdSessionFK))
                        {
                            TSessionApplicant session =  db.TSessionApplicants.SingleOrDefault(f => f.IdSessionApplicant == sessionApplicant.IdSessionApplicant );
                            session.IdFactureGenerated = factureGenerated.IdFacture;
                        }
                    }
                    db.SaveChanges();
                    
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }


            
        }

        public static int GetAmountToPayByCustomerID(int customerId)
        {
            int amount = 0;
            using (KerriganDBEntities db = new KerriganDBEntities())
            {
                try
                {
                    vwAmountToPay entity = new vwAmountToPay();
                    entity = db.vwAmountToPays.SingleOrDefault(f => f.IdApplicantFK == customerId);
                    amount = (int)entity.Amount;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            return amount;

        }

        public static List<FactureDC> GetAllFactures()
        {
            List<FactureDC> list = new List<FactureDC>();
            using (KerriganDBEntities db = new KerriganDBEntities())
            {
                try
                {
                    list = CopyEntityToBo(db.vwGetFactureByCustomers.ToList());
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            return list;

        }

        public static List<FactureDC> GetCustomerFacture(int customerId)
        {
            List<FactureDC> list = new List<FactureDC>();

            using (KerriganDBEntities db = new KerriganDBEntities())
            {
                try
                {
                    List<int?> listIdFacture = new List<int?>();
                    listIdFacture = (from session in db.TSessionApplicants
                                            where session.IdApplicantFK == customerId
                               select session.IdFactureGenerated).Distinct().ToList();
                    

                    foreach (TFactureGenerated entity in db.TFactureGenerateds.ToList())
                    {
                        FactureDC facture = new FactureDC();
                        if (listIdFacture.Contains(entity.IdFacture))
                        {
                            facture.Date = entity.Date;
                            facture.Id = entity.IdFacture;
                            facture.Amount = 0;
                            foreach (TFactureContent entityFacrtureContent in db.TFactureContents.ToList())
                            {
                                if (entityFacrtureContent.IdFactureGeneratedFK == entity.IdFacture)
                                {
                                    facture.Amount += entityFacrtureContent.Price;
                                }
                            }
                            list.Add(facture);
                        }
                        
                    }                       
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            return list;
        }

        public static byte[] getFactures(int id) {
            Paragraph NomPrenom;
            Paragraph Adress;
            Paragraph PCCity;
            List<Paragraph> elementFacture = new List<Paragraph>();
            Paragraph Total;

            Paragraph space = new Paragraph("");

            using (KerriganDBEntities db = new KerriganDBEntities())
            {
                try
                {

                    int tolalAmount = 0;
                    foreach (TFactureContent entityFacrtureContent in db.TFactureContents.ToList())
                    {
                        if (entityFacrtureContent.IdFactureGeneratedFK == id)
                        {
                            tolalAmount += entityFacrtureContent.Price;
                        }
                    }
                    List<TFactureContent> content = (from element in db.TFactureContents
                               where element.IdFactureGeneratedFK == id
                               select element).ToList();
                    TCustomer customer = (from session in db.TSessionApplicants
                                          where session.IdFactureGenerated == id
                                          select session.TCustomer).Distinct().First();
                    NomPrenom = new Paragraph(customer.TPerson.LastName + " " + customer.TPerson.FirstName);
                    Adress = new Paragraph(customer.TPerson.Adress);
                    PCCity = new Paragraph(customer.TPerson.PostCode + " "+customer.TPerson.City);
                    PCCity.SpacingAfter = 50;
                    Total = new Paragraph("Total : " + tolalAmount.ToString(), FontFactory.GetFont("ARIAL", 7));
                    Total.Alignment = Element.ALIGN_RIGHT;
                    Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("facture_"+id+".pdf", FileMode.Create));
                    doc.Open();
                    //nom + prenom
                    doc.Add(NomPrenom);
                    //adress
                    doc.Add(Adress);
                    //ville +cp
                    doc.Add(PCCity);
                    //espace
                    doc.Add(space);
                    doc.Add(space);
                    //liste element facture
                    Font font8 = FontFactory.GetFont("ARIAL", 7);
                      //Craete instance of the pdf table and set the number of column in that table
                    PdfPTable PdfTable = new PdfPTable(2);
                    PdfPCell PdfPCell = null;
                    PdfPCell = new PdfPCell(new Phrase(new Chunk("Designation", font8)));
                    PdfTable.AddCell(PdfPCell);
                    PdfPCell = new PdfPCell(new Phrase(new Chunk("Price", font8)));
                    PdfTable.AddCell(PdfPCell);
                    for (int rows = 0; rows < content.Count; rows++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk((content[rows] as TFactureContent).Designation, font8)));
                            PdfTable.AddCell(PdfPCell);
                            PdfPCell = new PdfPCell(new Phrase(new Chunk((content[rows] as TFactureContent).Price.ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                    }
                    PdfTable.SpacingBefore = 15f;
                    doc.Add(PdfTable);
                    //espace
                    doc.Add(space);
                    //total
                    doc.Add(Total);
                    doc.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            return File.ReadAllBytes("facture_"+id+".pdf");
        }

        public static FactureDC CopyEntityToBo(vwGetFactureByCustomer entity)
        {
            FactureDC bo = new FactureDC();

            try
            {
                bo.Id = entity.IdFacture;
                bo.Date = entity.Date;
                bo.Amount = (int)entity.Amount;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return bo;
        }
        public static List<FactureDC> CopyEntityToBo(List<vwGetFactureByCustomer> entities)
        {
            List<FactureDC> bo = new List<FactureDC>();
            try
            {
                foreach (vwGetFactureByCustomer entity in entities)
                {
                    bo.Add(CopyEntityToBo(entity));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return bo;
        }
        public static vwGetFactureByCustomer CopyBoToEntity(FactureDC bo)
        {
            vwGetFactureByCustomer entity = new vwGetFactureByCustomer();

            try
            {
                entity.IdFacture = bo.Id;
                entity.Date = bo.Date;
                entity.Amount = bo.Amount;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return entity;
        }
    }

}
